package com.cnd.scm.datasource;


import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.cnd.scm.jdbcprocessor.helper.SqlHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @version V1.0
 * @ClassName: DefaultDataSourceConfig
 * @Description:TODO()
 * @author: 李启联
 * @date: 2019-12-19 15:35
 * @Copyright: Copyright (C), 2019 Xiamen C&D Information Technology co.,Ltd. All rights reserved.
 * 申明：本内容未经授权,禁止外泄以及用于其他商业项目.
 */
@Configuration
@AutoConfigureAfter(value= {MultiDataSourceConfig.class})
@ConditionalOnMissingBean(MultiDataSourceConfig.class)
@Slf4j
@ConfigurationProperties("spring.datasource")
public class DefaultDataSourceConfig {

    public DefaultDataSourceConfig() {
        System.out.println("DefaultDataSourceConfig Created ...");
        log.info("DefaultDataSourceConfig Created ...");
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    @ConditionalOnProperty(name = "spring.datasource.druid")
    public DataSource dataSource(){
        return DruidDataSourceBuilder.create().build();
    }


    private String dbParamterPrefix = "";
    public String getDbParamterPrefix() {
        return dbParamterPrefix;
    }
    public void setDbParamterPrefix(String dbParamterPrefix) {
        this.dbParamterPrefix = dbParamterPrefix;
    }

    @Bean(name="sqlHelper")
    public SqlHelper sqlHelper(@Autowired DataSource dataSource) {
        SqlHelper sqlHelper = new SqlHelper();
        sqlHelper.setDataSource(dataSource);
        if(dbParamterPrefix != null && dbParamterPrefix.trim().length() > 0)
            sqlHelper.setDbParamterPrefix(dbParamterPrefix);
        return sqlHelper;
    }

    @Bean // 将数据源纳入spring事物管理
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource")  DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
